package com.smart.oil.service.impl;

import com.github.pagehelper.PageHelper;
import com.smart.oil.entity.SmTech;
import com.smart.oil.exception.BusinessException;
import com.smart.oil.exception.code.BaseResponseCode;
import com.smart.oil.mapper.SmTechMapper;
import com.smart.oil.service.TechService;
import com.smart.oil.utils.PageUtil;
import com.smart.oil.vo.req.TechAddReqVO;
import com.smart.oil.vo.req.TechPageReqVO;
import com.smart.oil.vo.req.TechUpdateReqVO;
import com.smart.oil.vo.resp.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;


@SuppressWarnings("ALL")
@Service
@Slf4j
public class TechServiceImpl implements TechService {


    @Autowired
    private SmTechMapper smTechMapper;

    @Override
    public PageVO<SmTech> pageInfo(TechPageReqVO vo) {

        PageHelper.offsetPage(vo.getPageNum(),vo.getPageSize());
        List<SmTech> smTeches =smTechMapper.selectAll(vo);
        return PageUtil.getPageVO(smTeches);
    }

    @Override
    public void addTech(TechAddReqVO vo) {
        SmTech smTech=new SmTech();
        BeanUtils.copyProperties(vo,smTech);
        smTech.setId(UUID.randomUUID().toString());
        smTech.setCreateTime(new Date());
        int i = smTechMapper.insertSelective(smTech);
        if(i!=1){
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
    }

    @Override
    public SmTech detailInfo(String id) {
        //通过id获取技术信息
        SmTech smTech = smTechMapper.selectByPrimaryKey(id);
        if(smTech==null){
            log.error("传入 的 id:{}不合法",id);
            throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        return smTech;
    }

    @Override
    public void updateTech(TechUpdateReqVO vo) {
        //保存更新的技术信息
        SmTech smTech=smTechMapper.selectByPrimaryKey(vo.getId());
        if (null==smTech){
            log.error("传入 的 id:{}不合法",vo.getId());
            throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        BeanUtils.copyProperties(vo,smTech);
        smTech.setUpdateTime(new Date());
        int count=smTechMapper.updateByPrimaryKeySelective(smTech);
        if(count!=1){
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletedTech(String techId) {
        //就更新删除的角色数据
        SmTech smTech=new SmTech();
        smTech.setId(techId);
        smTech.setDeleted(0);
        smTech.setUpdateTime(new Date());
        int count = smTechMapper.updateByPrimaryKeySelective(smTech);
        if(count != 1){
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
    }
}